package main

import (
	"errors"
	"fmt"

	"github.com/dcfn/req"
	"github.com/tidwall/gjson"
	"github.com/widuu/goini"

	"encoding/base64"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

type result struct {
	Rest      string
	Stime     time.Time
	Etime     time.Time
	Totaltime string
}

func main() {
	//fmt.Println("hello world !")

	if len(os.Args) == 3 {
		path := os.Args[2]
		rest := baiduASR(path)
		fmt.Println(rest.Rest)
		//fmt.Println(rest.Totaltime)
	} else {
		fmt.Println("usage: asr \"\" filename.wav")
	}

}
func baiduASR(path string) result {
	result := result{}
	err, token, cuid := access_token() //"24.0f96f700b1d5d7880ffd6916d8160f7a.2592000.1518080458.282335-10258516"
	if err == nil {
		filebyte, filelen := readfile(path)
		speech := base64.StdEncoding.EncodeToString(filebyte)
		//req.Debug = true
		url := "http://vop.baidu.com/server_api"
		headers := req.Header{
			"Content-Type": "application/json",
		}
		params := req.Param{
			"format":  "wav",
			"rate":    8000,
			"channel": 1,
			"cuid":    cuid,
			"token":   token,
			"len":     filelen,
			"speech":  speech,
		}

		result.Stime = time.Now()
		r, _ := req.Post(url, headers, req.BodyJSON(params))
		result.Etime = time.Now()
		result.Totaltime = result.Etime.Sub(result.Stime).String()
		result.Rest = gjson.Get(r.String(), "result").String()

	} else {
		result.Rest = err.Error()
	}
	return result
	//fmt.Println("request baiduASR server response :",r.String())
}
func readfile(path string) ([]byte, int) {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	filen := len(fd)
	return fd, filen
}
func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		println(err)
	}
	if runtime.GOOS == "linux" {
		dir += "/"
	} else {
		dir += "\\"
	}
	return dir

}

func access_token() (error, string, string) {
	goini := goini.SetConfig(GetCurrentDirectory() + "./bd.ini")
	ak := goini.GetValue("Params", "appKey")
	sk := goini.GetValue("Params", "secretKey")
	url := goini.GetValue("Params", "token_url")
	cuid := goini.GetValue("Params", "cuid")
	requrl := url + "?grant_type=client_credentials&client_id=" + ak + "&client_secret=" + sk + "&"
	//fmt.Println(requrl)
	headers := req.Header{
		"Content-Type": "application/json; charset=UTF-8",
	}

	access_token, err := req.Post(requrl, headers)
	if err != nil {
		return err, "get access_token fail..", ""
	}

	rspbody, _ := access_token.ToString()
	//fmt.Println("response message :",rspbody)
	token := gjson.Get(string(rspbody), "access_token")
	error_code := gjson.Get(string(rspbody), "error")
	if len(error_code.String()) > 1 {
		return errors.New("get token error :" + error_code.String()), "", ""
	}
	return nil, token.String(), cuid
}
